import logging
import os
import time

from api.scheduler import ProdSchedule


logger = logging.getLogger('django')


def exit_prod_service(current_mould):
    consumer = current_mould.consumer
    # listener = current_mould.listener
    if current_mould.is_order_running:
        # ProdSchedule.stop()
        # 先让producer停下来,producer就不会往队列里追加样本,接着让consumer停下来,

        # 取消了监听串口
        # # 有时候listener突然挂了，怀疑是操作不规范或者前端没断开websocket
        # if listener and listener.is_alive():
        #     listener.stop()
        #     listener.join()

        # producer线程中有样本计数功能需要保持，故不退出
        # if producer and producer.is_alive():
        #     producer.stop()
        #     producer.join()
        if consumer and consumer.running.is_set():
            consumer.stop()
            consumer.sample_list = []
            # 将调用join的线程consumer线程优先执行，项目当前正在执行的线程阻塞，直到调用join方法的线程执行完毕
            # 这个地方如果优先执行，则在前端调用这个接口时，会阻塞！！！
            # consumer.join()
        current_mould.is_order_running = False
        logger.info(f'工单{current_mould.mould_code} 已经退出')


# def exit_prod_service(current_mould):
#     a = "123456"
#     b = "bash start.sh"
#     os.system("echo %s|sudo -S %s" % (a, b))
#     print('重新开启python！')
